
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"
 
;
; Main code
;
begin

  year = "1991"  

  load "load_info.ncl" 

  acm = (/"01","02","03","04","05","06","07","08","09","10","11","12"/)

  if (year.ne."1992" .and. year.ne."1996") then 
     ndm = (/ 31,  28,  31,  30,  31,  30,  31,  31,  30,  31,  30,  31 /)
  else
     ndm = (/ 31,  29,  31,  30,  31,  30,  31,  31,  30,  31,  30,  31 /)
  end if 

  c31 = (/"01","02","03","04","05","06","07","08","09","10", \
          "11","12","13","14","15","16","17","18","19","20", \
          "21","22","23","24","25","26","27","28","29","30", \
          "31" /)

  c30 = (/"01","02","03","04","05","06","07","08","09","10", \
          "11","12","13","14","15","16","17","18","19","20", \
          "21","22","23","24","25","26","27","28","29","30" /)

  c29 = (/"01","02","03","04","05","06","07","08","09","10", \
          "11","12","13","14","15","16","17","18","19","20", \
          "21","22","23","24","25","26","27","28","29" /)

  c28 = (/"01","02","03","04","05","06","07","08","09","10", \
          "11","12","13","14","15","16","17","18","19","20", \
          "21","22","23","24","25","26","27","28" /)


;
; Read population data into an array of strings, removing the 
; first 4 lines and the last 2 lines (header and footer).
;
  data = readAsciiTable("bmd"+year+".dat",1,"string",(/0,0/))

  ; Replace commas with an empty string.
  ;data = str_sub_str(data,",","")

  hh   = stringtointeger(str_get_field(data,1," ")) 
  ss   = stringtointeger(str_get_field(data,2," "))
  date =                 str_get_field(data,3," ")
  rna  = stringtofloat  (str_get_field(data,4," "))

  hh   = where(ss.ge.30,hh+1,hh) 
  ss   = 0 

  if (year.ne."1992" .and. year.ne."1996") then 
  ynd  = 365 
  else
  ynd  = 366 
  end if 

  nm   = 12 

  rnb  = new((/ynd*24/),"float") 
  rnb  = -999 

  print("date: "+date+" "+hh+" "+ss+" "+rna) 


  ix = 0 ;; index for new data  


  nt = dimsizes(hh(:,0)) 
  nh = 24 

  do it = 0, nt-1 

  ;; 2000-01-01
  ;; 0123456789 

  iy = 0 ;; index for original data  

  adate = stringtochar(date(it,0))
  ayy   = chartostring(adate(0:3)) 
  amm   = chartostring(adate(5:6)) 
  add   = chartostring(adate(8:9)) 

  ky    = stringtointeger(ayy)  
  km    = stringtointeger(amm)  
  kd    = stringtointeger(add)   
  kh    = hh(it,0)  

  ;print("ky,km,kd: "+ky+" "+km+" "+kd)
 
  do im = 0, nm-1 
    do id = 0, ndm(im)-1 
    do ih = 0, nh-1 

     if(km.eq.im+1) then 
     if(kd.eq.id+1) then 
     if(kh.eq.ih) then 
        print("km: "+km+" kd: "+kd+" ix,iy: "+ix+" "+iy+" rn: "+rna(ix,0)) 
        rnb(iy) = rna(ix,0)   
     end if 
     end if 
     end if 
 
     iy = iy + 1 
    end do ;; do ih  
    end do ;; do id  
  end do ;; do im  

  ix = ix + 1

  end do ;; do it  


  asciiwrite("radon_bermuda_"+year+".dat",rnb) 

  filenamo = "out.nc" 

  filo = addfile(filenamo,"c") 

  system("rm "+filenamo) 

  filo->rn_1m=rnb 

end



